/*年轻人，只管向前看，不要管自暴自弃者的话*/

import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:event_bus/event_bus.dart';
import 'package:get/get.dart';

import '../../mixin/toast_mixin.dart';
import '../../util/log_util.dart';

///create by itz on 2024/1/3 17:20
///具有状态控制和网络请求能力的controller，等价MVVM中的ViewModel
abstract class BaseController<T> extends SuperController with ToastMixin {
  late EventBus eventBus;

  List<StreamSubscription>? streamSubList;
  RxString barTitleString = "标题".obs;
  late ConnectivityResult? networkStatus;

  static bool isVisible = true; // 是否前台可见

  @override
  void onInit() async {
    super.onInit();
    LogD('onInit');
    await getNetworkStatus().then((value) {});
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      LogD("onConnectivityChanged result.name${result.name}");
      networkStatus = result;
      if (result == ConnectivityResult.mobile) {
      } else if (result == ConnectivityResult.wifi) {
      } else {
        // 如果没有网络连接
        LogD("onConnectivityChanged 没有网络连接");
        badNetwork();
      }
      LogD("networkStatus $networkStatus");
    });
  }

  Future<ConnectivityResult> getNetworkStatus() async {
    ConnectivityResult result;
    try {
      result = await Connectivity().checkConnectivity();
    } on Exception catch (e) {
      LogD(e.toString());
      result = ConnectivityResult.none;
    }
    networkStatus = result;
    LogD('getNetworkStatus $networkStatus');
    return result;
  }

  void badNetwork() {}

  @override
  void onDetached() {
    LogD('BaseController onDetached APP结束时调用');
  }

  @override
  void onInactive() {
    /// 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
    LogD('BaseController onInactive 不活跃的');
  }

  @override
  void onResumed() {
    LogD('BaseController onResumed 从后台切换前台，界面可见');
    isVisible = true; // 是否前台可见
  }

  @override
  void onHidden() {
    LogD('BaseController onHidden()');
  }

  @override
  void onPaused() {
    LogD('BaseController onPaused 界面不可见，后台');
    isVisible = false; // 是否前台可见
  }

  @override
  void onReady() {
    super.onReady();
    LogD('onReady');
    if (useEventBus()) {
      eventBus = Get.find<EventBus>();
    }
    loadNet();
  }

  void loadNet();

  @override
  void onClose() {
    super.onClose();
    //解订阅EventBus
    disposeEventBus();
    LogD('onClose');
  }

  void showLoading() {
    change(null, status: RxStatus.loading());
  }

  ///是否使用GetX查找EventBus
  bool useEventBus() => false;

  ///管理Eventbus解订阅
  void addStreamSub(StreamSubscription? streamSubscription) {
    streamSubList ??= [];
    if (streamSubscription != null) {
      streamSubList?.add(streamSubscription);
    }
  }

  ///解订阅StreamSubscription--关联EventBus
  void disposeEventBus() {
    streamSubList?.forEach((element) {
      element.cancel();
    });
  }
}
